const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 配送统计
router.post('/deliver/gpCargos', async ctx => {
    let tenantId = ctx.user.tenantId;
    let billDate = ctx.request.body.billDate
    let deliverId = ctx.request.body.deliverId
    let strIds = await tool.relCompany(tenantId);
    if (strIds.length === 0) {
        return ctx.err('还没有关联配送公司');
    }
    let admin = await db.models['admin'].findOne({
        where: {
            id: deliverId
        }
    })
    let str = ' '
    if(admin) {
        str = ` and deliverNames like '%${admin.name}%' `
    }
    let tids = strIds.join(',')
    let sql = `
        SELECT billNo,deliverNames,licence,case when state=2 then '已确认' else '送货中' end state,invId,qty,invName,spec,unit2,unit1 from 
        (
            select a.billNo,a.licence,a.deliverNames,a.state,invId,sum(qty) qty,invName,spec,unit1,unit2 from (
                select a.billNo,a.deliverNames,a.state, a.licence,(c.qty*c.calNum) qty,c.invId,d.name invName,d.spec,d.unit1,d.unit2 from cargo a 
                    inner join cargo_invoice b on a.id=b.cargoId  
                inner join invoice_info c on b.iid=c.iid inner join goods d on c.invId=d.id and a.tenantId in(${tids}) 
             and a.billDate between '${billDate[0]}' and '${billDate[1]}' and a.state<>3 ${str}
            ) a GROUP BY a.billNo,a.licence,a.deliverNames,a.state,invId,invName,spec,unit1,unit2
        ) a  
        `
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', ret);
})


module.exports = router;
